package com.luli.kafkaStudy;

import org.apache.kafka.clients.producer.*;
import org.apache.kafka.common.serialization.StringSerializer;

import java.util.Properties;
import java.util.concurrent.Future;

/**
 * @Projectname: elasticsearch
 * @Filename: demo01
 * @Author: 陆离
 * @Data:2023/4/7 15:50:36
 */
public class ProducerFastStart {
    private static final String brokerList = "192.168.146.147:9092";
    private static final String topic = "luliTest";

    public static void main(String[] args) {
        Properties properties = new Properties();
        //设置key序列化
//        properties.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
        properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
        //设置重试参数
        properties.put(ProducerConfig.RETRIES_CONFIG, 10);
        //设置值序列化器
        //properties.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");
        properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
        //设置集群地址
//        properties.put("bootstrap.servers", brokerList);
        properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, brokerList);
        KafkaProducer<String, String> producer = new KafkaProducer<>(properties);
        ProducerRecord record = new ProducerRecord<>(topic, "key-demo", "测试数据传入66666");
        try {
            //发送
/*            Future<RecordMetadata> send = producer.send(record);
            RecordMetadata recordMetadata = send.get();
            System.out.println("topic" + recordMetadata.topic());
            System.out.println("partition(分区)" + recordMetadata.partition());
            System.out.println("offset" + recordMetadata.offset());*/
            //异步发送，防止线程堵塞
            producer.send(record, new Callback() {
                @Override
                public void onCompletion(RecordMetadata recordMetadata, Exception exception) {
                    if (exception == null){
                        System.out.println("topic" + recordMetadata.topic());
                        System.out.println("partition(分区)" + recordMetadata.partition());
                        System.out.println("offset" + recordMetadata.offset());
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            producer.close();
        }
    }

}
